package com.gitlab.lucky.common.task;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.text.UnicodeUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.gitlab.lucky.common.dao.model.*;
import com.gitlab.lucky.common.enums.CodeEnum;
import com.gitlab.lucky.common.enums.Constant;
import com.gitlab.lucky.common.service.ConfigDataService;
import com.gitlab.lucky.common.service.PlatformDataService;
import com.gitlab.lucky.common.redis.RedisService;
import com.gitlab.lucky.eleme.model.LuckyResult;
import com.gitlab.lucky.eleme.model.PromotionRecords;
import com.gitlab.lucky.eleme.service.ElemCookieService;
import com.gitlab.lucky.eleme.service.ElemHandleService;
import com.gitlab.lucky.eleme.service.LuckyRecordService;
import com.gitlab.lucky.weixin.service.WeixinGzhIntegrationRecordService;
import com.gitlab.lucky.weixin.service.WeixinGzhUserService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import tk.mybatis.mapper.entity.Example;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

/**
 * @program: lucky
 * @author: Mr.Han
 * @create: 2018-11-05 22:20
 **/
@Component
public class Task {
    @Value("${task}")
    private Boolean task;
    public static final Logger LOGGER = LoggerFactory.getLogger(Task.class);
    @Autowired
    private WeixinGzhUserService weixinGzhUserService;
    @Autowired
    private ElemCookieService elemCookieService;
    @Autowired
    private RedisService redisService;
    @Autowired
    private PlatformDataService platformDataService;
    @Autowired
    private LuckyRecordService luckyRecordService;
    @Autowired
    private ConfigDataService configDataService;
    @Autowired
    private WeixinGzhIntegrationRecordService weixinGzhIntegrationRecordService;
    @Autowired
    private ElemHandleService elemHandleService;

    /**
     * 初始化签到，小号存redis
     */
    @Scheduled(cron = "0 0 0 1/1 * ? ")
    public void timerToNow() {
        if(task){
            //用户签到初始化
            LOGGER.info("start---初始化用户签到信息---start");
            initSignIn();
            LOGGER.info("end---初始化用户签到信息---end");
            //ck存入redis
            LOGGER.info("start---存入小号数据到redis---start");
            forLeftPush(Constant.ELEM_CK_KEY);
            LOGGER.info("end---存入小号数据到redis---end");
            //清除没用的本地图片
            LOGGER.info("start---删除本地邀请码图片---start");
            deleteImg();
            LOGGER.info("end---删除本地邀请码图片---end");
            LOGGER.info("start---刷新领取记录---start");
            resetLuckyRecord(luckyRecordService.selectLucky());
            LOGGER.info("end---刷新领取记录---end");
            iccGame();
        }
    }

    public static void main(String[] args) {
        iccGame();
    }
    private static void iccGame() {
        String body = HttpUtil.createPost("http://vip.silkroad.iccgame.com/user/senditem/")
                .cookie("PHPSESSID=c8t8blbre3cavfne0aibsfal76; __ticket=eSAZ6Q2RcaUTjR8Q4N%2F6zvq%2FXBtPwIgQ0Dqvk99gV83mjA96PCjMxY3EnO8j9uzZCrHMVBvQgpsiLy84DmehKXaMUja5LCt5%2FkMxuw6SCUZj2PY2%2FWaX0iL19CJA5iaVju6sfpcH7U%2FUq10wbHaHO7kWq4nUV9FoQmC7VG%2BpI08%3D; returnUrl=http%3A%2F%2Fsecurity.iccgame.com%2Fquestion%2Fnew")
                .header("Content-Type","application/x-www-form-urlencoded; charset=UTF-8")
                .header("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.90 Safari/537.36")
                .form("rank",3)
                .form("sid",325)
                .form("char_id",3078338)
                .form("char_name","理想三旬i")
                .execute().body();
        String decode = null;
        try {
            decode = URLDecoder.decode(body, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        String s = UnicodeUtil.toString(decode);
        LOGGER.info(s);
    }
    /**
     * 刷新AccessToken每1小时55分钟执行一次
     */
    @Scheduled(initialDelay = 1, fixedDelay = (2 * 60 * 60 * 1000) - (5 * 60 * 1000))
    public void queryAccessToken() {
        if (task) {
            LOGGER.info("start---获取AccessToken---start");
            List<PlatformData> platformData = platformDataService.selectAll();
            for (PlatformData platformDatum : platformData) {
                String url = String.format(Constant.GET_ACCESS_TOKEN_URL, platformDatum.getAppId(), platformDatum.getAppSceart());
                String result = HttpUtil.get(url);
                JSONObject json = JSON.parseObject(result);
                String accessToken = json.getString("access_token");
                Integer expires_in = json.getInteger("expires_in");
                if (!StringUtils.isBlank(accessToken)) {
                    redisService.set(Constant.WX_ACCESS_TOKEN_KEY + platformDatum.getPlatform(), accessToken);
                    LOGGER.info("存储AccessToken:{},有效时间:{}秒", accessToken, expires_in);
                } else {
                    LOGGER.info("获取AccessToken失败:{}", result);
                }
            }
            LOGGER.info("end---获取AccessToken---end");
        }
    }


    @Scheduled(cron = "0 0/10 * * * ? ")
    public void rankingList() {
        if (task) {
            LOGGER.info("start---刷新领取记录金额,返还积分等---start");
            //查询今天手气最佳存在的记录
            List<LuckyRecord> luckyRecords = luckyRecordService.selectByNow();
            LOGGER.info("一共需要刷新{}条记录", luckyRecords.size());
            resetLuckyRecord(luckyRecords);
            LOGGER.info("end---刷新领取记录金额,返还积分等---end");
        }
    }

    public void deleteImg() {
        try {
            String s = "rm -rf /root/.jenkins/workspace/lucky/target/classes/image/wx*";
            Process ps = Runtime.getRuntime().exec(s);
            ps.waitFor();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void initSignIn() {
        WeixinGzhUser weixinGzhUser = new WeixinGzhUser();
        weixinGzhUser.setIsSignIn(Constant.SIGN_IN_FALSE);
        Example example2 = new Example(WeixinGzhUser.class);
        example2.createCriteria().andEqualTo("isSignIn", Constant.SIGN_IN_TRUE);
        weixinGzhUserService.updateByExampleSelective(weixinGzhUser, example2);
    }

    public void forLeftPush(String key) {
        redisService.del(key);
        Example example = new Example(ElemCookie.class);
        example.createCriteria().andIsNotNull("sid").andEqualTo("isDelete", Constant.FALSE);
        List<ElemCookie> elemCookies = elemCookieService.selectByExample(example);
        for (int i = 0; i < 5; i++) {
            Collections.shuffle(elemCookies);
            redisService.lpush(Constant.ELEM_CK_KEY, elemCookies);
        }
    }
    /**
     * 刷新领取记录金额
     */
    public void resetLuckyRecord(List<LuckyRecord> luckyRecords) {
        for (LuckyRecord luckyRecord : luckyRecords) {
            JSONObject config = configDataService.getConfig(luckyRecord.getPlatform());
            //请求饿了么
            LuckyResult luckyResult = elemHandleService.requestLuckyUrl(luckyRecord.getSn(), luckyRecord.getCkSid(), luckyRecord.getCkOpenid(), luckyRecord.getCkElemkey());
            //已经抢过
            if (luckyResult.getRet_code() == 2) {
                //该红包领取记录
                ArrayList<PromotionRecords> promotion_records = luckyResult.getPromotion_records();
                //手气最佳已被抢
                if (CollectionUtil.isNotEmpty(promotion_records) &&
                        promotion_records.size() >= luckyRecord.getLuckyNumber()) {
                    //手气最佳小于元
                    if (promotion_records.get(luckyRecord.getLuckyNumber() - 1).getAmount() < config.getDouble(Constant.MIN_AMOUNT)) {
                        //查询用户
                        WeixinGzhUser weixinGzhUser = weixinGzhUserService.getWxUserInfoByOpenId(luckyRecord.getOpenid(), luckyRecord.getPlatform());
                        //返还积分
                        weixinGzhUser.setIntegration(weixinGzhUser.getIntegration() + config.getInteger(Constant.MIN_COUNT));
                        weixinGzhUserService.updateByPrimaryKeySelective(weixinGzhUser);
                        //积分流水
                        WeixinGzhIntegrationRecord weixinGzhIntegrationRecord = new WeixinGzhIntegrationRecord();
                        weixinGzhIntegrationRecord.setCreateTime(new Date());
                        weixinGzhIntegrationRecord.setIntegration("+"+config.getString(Constant.MIN_COUNT));
                        weixinGzhIntegrationRecord.setIntegrationBalance(weixinGzhUser.getIntegration());
                        weixinGzhIntegrationRecord.setPlatform(luckyRecord.getPlatform());
                        weixinGzhIntegrationRecord.setOpenId(weixinGzhUser.getOpenid());
                        weixinGzhIntegrationRecord.setType(CodeEnum.COMPENSATION_INTEGRATION.getCode());
                        weixinGzhIntegrationRecordService.insertSelective(weixinGzhIntegrationRecord);
                        //消息通知
                        //LOGGER.info("返还积分成功---请求者:{},SN:{},小红包金额:{}", luckyRecord.getOpenid(), luckyRecord.getSn(), promotion_records.get(luckyRecord.getLuckyNumber() - 1).getAmount());
                    }
                    LOGGER.info("手气最佳已被抢，金额为:{}", promotion_records.get(luckyRecord.getLuckyNumber() - 1).getAmount());
                    luckyRecord.setLuckyMoney(promotion_records.get(luckyRecord.getLuckyNumber() - 1).getAmount());
                    luckyRecordService.updateByPrimaryKeySelective(luckyRecord);
                } else {
                    luckyRecord.setCount(luckyRecord.getCount() + 1);
                    luckyRecordService.updateByPrimaryKeySelective(luckyRecord);
                }
            } else {
                LOGGER.info("刷新返回RET_CODE:{}", luckyResult.getRet_code());
                luckyRecordService.deleteByPrimaryKey(luckyRecord.getId());
            }
        }
    }

}
